package sktit.practice.jpaint.shape;

import java.util.ArrayList;
import java.util.Arrays;

import org.eclipse.swt.graphics.Point;

import sktit.practice.jpaint.util.ShapeUtils;

public class Polygon extends AbstractShape {
	
	protected ArrayList<Point> vertex;
	
	public Polygon(ArrayList<Point> aVertex)
	{
		vertex = new ArrayList<Point>();
		for(Point p : aVertex)
		{
			vertex.add(new Point(p.x, p.y));
		}
	}
	
	@Override
	public double getPerimeter()
	{
		double perimeter = 0;
		int length = vertex.size();
		
		for(int i = 0; i < length -1; i++)
		{
			perimeter += ShapeUtils.getLine(vertex.get(i), vertex.get(i+1));
		}
		
		perimeter += ShapeUtils.getLine(vertex.get(length -1), vertex.get(0));
		
		return perimeter;
	}
	
	@Override
	public double getArea()
	{
		double area = 0;
		
		for(int i = 1; i < vertex.size()-1;i++)
		{
			Polygon p = new Polygon(new ArrayList<Point>(Arrays.asList(vertex.get(0), vertex.get(i), vertex.get(i+1))));
			
			double halfPerimeter = p.getPerimeter()/2;
			
			double a = ShapeUtils.getLine(vertex.get(0), vertex.get(i));
			double b = ShapeUtils.getLine(vertex.get(i), vertex.get(i+1));
			double c = ShapeUtils.getLine(vertex.get(0), vertex.get(i+1));
			
			area += Math.sqrt(halfPerimeter*(halfPerimeter - a)*(halfPerimeter - b)*(halfPerimeter - c));
		}
		
		return area;
	}
	
	@Override
	public Point[] getBorder()
	{
		Point[] border = new Point[vertex.size()];
		vertex.toArray(border);
		return border;
		
		
	}
	
}
